package com.example.smartgreenhouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.smartgreenhouse.entity.DeviceCurrent;
import com.example.smartgreenhouse.exception.BusinessException;
import com.example.smartgreenhouse.mapper.DeviceCurrentMapper;
import com.example.smartgreenhouse.service.DeviceCurrentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class DeviceCurrentServiceImpl implements DeviceCurrentService {
    private final DeviceCurrentMapper mapper;

    @Override
    public DeviceCurrent getDeviceStatus(String deviceType, Long deviceId) {

        DeviceCurrent fanCurrent = mapper.selectOne(new LambdaQueryWrapper<DeviceCurrent>()
                .eq(DeviceCurrent::getDeviceType, deviceType)
                .eq(DeviceCurrent::getDeviceId, deviceId));
        if(fanCurrent == null)
            throw new BusinessException(deviceId + "号"+ getName(deviceType) + "数据不存在");
        return fanCurrent;
    }

    @Override
    @Transactional
    public void upsertDeviceStatus(DeviceCurrent entity) {
        if (mapper.updateDeviceStatus(entity) == 0) {
            mapper.insert(entity);
        }
    }

    private String getName(String deviceType) {
        switch (deviceType) {
            case "fan":
                return "风扇";
            case "water_pump":
                return "水泵";
            case "full_spectrum_LED_light":
                return "LED灯";
            default:
                return "";
        }
    }
}